package org.ssmd3.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.ssmd3.pojo.News;
import org.ssmd3.pojo.NewsType;
import org.ssmd3.service.NewsService;
import org.ssmd3.service.NewsTypeService;
import org.ssmd3.util.PageTool;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/news")

public class NewsController {
    @Resource
    NewsTypeService newsTypeService;
    @Resource
    NewsService newsService;

    @RequestMapping("/update")
    public String update(Model model,Integer id){
        News news=newsService.getOneNews(id);
        List<NewsType> plist=newsTypeService.getAllNewsTypeList();
        model.addAttribute("plist",plist);
        model.addAttribute("news",news);
        return "/news/update";
    }

    @RequestMapping("/doupdate")
    public String doupdate(Model model, News news, HttpSession session,@RequestParam(value = "a_newsImg",required = false)
            MultipartFile file){
        //1.保存图片
        if (file!=null){//保存图片
            String path=session.getServletContext().getRealPath("statics/upload");//获取文件路径位置
            String oldFileName=file.getOriginalFilename();//获取原文件名
            int mIndex=oldFileName.lastIndexOf(".");
            String nextName=oldFileName.substring(mIndex+1);

            if (nextName.equals("jpg")
                    ||nextName.equals("png")
                    ||nextName.equals("gif")){
                //新文件的文件名
                String fileName=new Date().getTime()+"_"+(int)(Math.random()*1000000)+"."+nextName;
                File file1=new File(path,fileName);//创建新的文件，用于接收用户上传的文件流
                if (!file1.exists()) {
                    file1.mkdirs();
                 }
                try {
                    file.transferTo(file1);
                    //上传成功
                    news.setNewsImg(fileName);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //2.修改新闻
        newsService.update(news);
        return "redirect:/news/list";
    }

    @RequestMapping("/dodelete")
    @ResponseBody
    public String doDelete(Model model,int id){
        try {
            newsService.delete(id);
            return "1";
        }catch (Exception e){
            return "0";
        }
    }

    @RequestMapping("dodeleteall")
    @ResponseBody
    public String doDeleteAll(String ids){
        String[] idsArray=ids.split(",");
        try {
            newsService.deleteAll(idsArray);
            return "1";
        }catch (Exception e){
            e.printStackTrace();
            return "0";
        }
    }


    @RequestMapping("/save")
    public String save(Model model){
        List<NewsType> plist=newsTypeService.getAllNewsTypeList();
        model.addAttribute("plist",plist);
        return "/news/save";
    }

    @RequestMapping("/dosave")
    public String doSave(Model model, News news, HttpSession session,@RequestParam(value = "a_newsImg",required = false)
            MultipartFile file){
        //1.保存图片
        if (file!=null){//保存图片
            String path=session.getServletContext().getRealPath("statics/upload");//获取文件路径位置
            String oldFileName=file.getOriginalFilename();//获取原文件名
            int mIndex=oldFileName.lastIndexOf(".");
            String nextName=oldFileName.substring(mIndex+1);

            System.out.println("后缀名:"+nextName);

            if (nextName.equals("jpg")
                    ||nextName.equals("png")
                    ||nextName.equals("gif")){
                //新文件的文件名
                String fileName=new Date().getTime()+"_"+(int)(Math.random()*1000000)+"."+nextName;
                File file1=new File(path,fileName);//创建新的文件，用于接收用户上传的文件流
                if (!file1.exists()){
                    file1.mkdirs();
                }
                try {
                    file.transferTo(file1);
                    //上传成功
                    news.setNewsImg(fileName);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //2.新增新闻
        newsService.save(news);
        return "redirect:/news/save";
    }


    @RequestMapping("/list")
    public String list(Model model,News news){

        int totalRecordCount=newsService.getRecordCount(news);
        PageTool pageTool=new PageTool(totalRecordCount,news.getCurrPageNo(),2);
        int startNum=pageTool.getStartRow();
        int pageSize=pageTool.getPageSize();
        news.setStarNum(startNum);
        news.setPageSize(pageSize);

        List<News> list=newsService.getNewsListByPage(news);
        List<NewsType> plist=newsTypeService.getAllNewsTypeList();

        model.addAttribute("list",list);
        model.addAttribute("plist",plist);
        model.addAttribute("news",news);
        model.addAttribute("pageTool",pageTool);
        model.addAttribute("prePages",pageTool.getPrePages());
        model.addAttribute("nextPages",pageTool.getNextPages());

        return "/news/list";
    }

    @RequestMapping("/edit")
    @ResponseBody
    public String editNews(String title,Integer id){

        try {
            News news = newsService.getOneNews(id);
            news.setTitle(title);
            newsService.update(news);
            return "1";
        }catch (Exception e){
            e.printStackTrace();

        }
        return "0";
    }

}